<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Task extends Base_Controller {

    public $sender;
    public $sender_address;
    public $receiver;
    public $receiver_address;
    public $subject;
    public $content;
    public $template_content;
    public $attachment;
    public $sendname;
    public $htmlbefore = '<!DOCTYPE html><html><head><meta charset="utf-8" /><style>* {margin: 0;padding: 0;}</style></head><body style="width: 100%;height: 100%;background: #f5f5f5;"><div style="width: 750px;margin: auto;overflow: hidden;background: #f5f5f5;text-align:center;padding:10px;">';
    public $htmlafter = '</div></body></html>';

    public function __construct() {
        parent::__construct();
        $this->load->library('phpmailer/PHPMailer.php');
        $this->load->library('phpmailer/POP3.php');
        $this->load->library('phpmailer/SMTP.php');
        if ($this->session->level == 99) {
            $this->sendname = 'EmailSu超级管理员';
        } else if ($this->session->level == 1 || $this->session->level == 50) {
            $sendnamearr = $this->common_model->getList('su_sendname', ['department_id' => $this->session->department_id]);
            $this->sendname = $sendnamearr[0]['send_name'];
        } else {
            $this->sendname = $this->session->username;
        }
    }

    public function index() {
        $where = [
            'department_id' => $this->session->department_id
        ];
        $this->data['group'] = $this->common_model->getList('su_group', $where);
        $this->data['template'] = $this->common_model->getList('su_template', $where);
        $this->load->view('public/header', $this->data);
        $this->load->view('pages/task');
    }

    public function log() {
        $this->data['loglist'] = $this->get_task_record();
        $this->load->view('public/header', $this->data);
        $this->load->view('pages/log');
    }

    public function send() {
        $redata = $this->httpcode;
        $department_id = $this->session->department_id;
        $group = $this->input->post('receiver');
        $uid = $this->session->id;
        $where_send = [
            'department_id' => $department_id,
            'status' => 1
        ];
        $where_receive = [
            'department_id' => $department_id,
            'status' => 1,
            'group_id' => $group,
            'enable' => 1
        ];

        $sender = $this->input->post('sender');
        $receiver = $this->input->post('receiver');
        $template = $this->input->post('template');
        $subject = $this->input->post('subject');
        $content = $this->input->post('content');

        switch ($sender) {
            case 1: {
                    //最新添加
                    $where_send['total_amount'] = 0;
                }
                break;
            case 2: {
                    //今日可用
                    $where_send['enable'] = 1;
                }
                break;
        }
        $this->sender = $this->address_model->addressInfo('su_sender', $where_send);
        $this->receiver = $this->address_model->addressInfo('su_receiver', $where_receive);
        $where = [
            'id' => $template
        ];
        $this->subject = $subject;
        $this->content = $content;
        $this->template_content = $this->template_model->getTemplateByid($where);
        $this->start_task();
        $redata['errno'] = 666;
        $redata['error'] = '执行任务成功!';
        echo json_encode($redata);
    }

    public function start_task() {
        $attachment = $this->template_content['attachment'];
        $is_messy = $this->template_content['is_messy'];
        $count = 0;
        foreach ($this->sender as $k => $v) {
            $receive_arr = [];
            $receive_arr = array_slice($this->receiver, $count * $this->data['webconfig'][0]['value'], $this->data['webconfig'][0]['value']);
            foreach ($receive_arr as $vr) {
                $senderInfo = [];
                $receiverInfo = [];
                $mail = new PHPMailer();
                $mail->isSMTP();
                $mail->SMTPAuth = TRUE;
                $mail->Host = $v['mail_host'];
                $mail->SMTPSecure = "ssl"; // 使用ssl协议方式
                $mail->Port = 465;
                $mail->CharSet = 'utf-8';
                $mail->Username = $v['approve_username'];
                $mail->Password = $v['approve_password'];
                $mail->From = $v['email'];
                $mail->FromName = $this->sendname; //发送人昵称
                $mail->isHTML(true); //邮件正文是否为html编码 注意此处是一个方法 不再是属性 true或false
                $mail->addAddress($vr['email']);
                $mail->Subject = $this->subject; //添加该邮件的主题
                $this->template_content['is_messy'] == 1 ? $mail->Body = $this->htmlbefore . add_disturb($this->content) . $this->htmlafter : $mail->Body = $this->htmlbefore . $this->content . $this->htmlafter; //添加邮件正文 
                if (!empty($attachment)) {
                    $attachment = './' . $attachment;
                    $mail->AddAttachment($attachment);
                }
                $state = $mail->send(); //发送命令 返回布尔值 
                $mail->smtpClose();
                $data = [
                    'sender_id' => $v['id'],
                    'receiver_id' => $vr['id'],
                    'sender' => $v['email'],
                    'receiver' => $vr['email'],
                    'create_time' => tnow(),
                    'department_id' => $this->session->department_id,
                    'uid' => $this->session->id,
                    'username' => $this->session->username
                ];
                if ($state) {
                    $data['isok'] = 1;
                } else {
                    $content = $mail->ErrorInfo;
                    $filename = './application/logs/' . date('Ymd') . ".log";
                    $fp = fopen($filename, 'a+');
                    fwrite($fp, $content);
                    fclose($fp);
                }
                $this->log_model->createLog('su_send_record', $data);
                if ($state) {
                    $where_sender = [
                        'id' => $v['id']
                    ];
                    $where_receiver = [
                        'id' => $vr['id']
                    ];
                    $senderInfo = $this->address_model->getAddress('su_sender', $where_sender);
                    $receiverInfo = $this->address_model->getAddress('su_receiver', $where_receiver);
                    $senderInfo['today_usage'] ++;
                    $senderInfo['total_usage'] ++;
                    $receiverInfo['today_usage'] ++;
                    $receiverInfo['total_usage'] ++;
                    $data_sender = [
                        'today_usage' => $senderInfo['today_usage'],
                        'total_usage' => $senderInfo['total_usage']
                    ];
                    if ($senderInfo['today_usage'] >= $this->data['webconfig'][0]['value'])
                        $data_sender['enable'] = 0;
                    $data_receiver = [
                        'today_usage' => $receiverInfo['today_usage'],
                        'total_usage' => $receiverInfo['total_usage']
                    ];
                    if ($receiverInfo['today_usage'] >= $this->data['webconfig'][1]['value'])
                        $data_receiver['enable'] = 0;
                    $this->address_model->updateAddress('su_sender', $where_sender, $data_sender);
                    $this->address_model->updateAddress('su_receiver', $where_receiver, $data_receiver);
                }
            }
            $count++;
        }
    }

    public function send_handy() {
        $redata = $this->httpcode;
        $sender = $this->input->post('sender');
        $receiver = $this->input->post('receiver');
        $approve_username = $this->input->post('approve_username');
        $approve_password = $this->input->post('approve_password');
        $subject = $this->input->post('subject');
        $content = $this->input->post('content');
        $attachment = $this->input->post('attachment');
        $smtp = $this->input->post('smtp');
        strtolower($smtp) == 'qq' ? $mail_host = 'smtp.qq.com' : $mail_host = 'smtp.163.com';
        if (!empty($attachment))
            $attachment = './uploads/mail_file/' . $attachment;
        $receiver_list = explode(';', $receiver);
        foreach ($receiver_list as $k => $v) {
            $mail = new PHPMailer();
            $mail->isSMTP();
            $mail->SMTPAuth = TRUE;
            $mail->Host = $mail_host;
            $mail->CharSet = 'utf-8';
            $mail->Username = $approve_username;
            $mail->Password = $approve_password;
            $mail->From = $sender;
            $mail->FromName = $this->sendname;
            $mail->isHTML(true); //邮件正文是否为html编码 注意此处是一个方法 不再是属性 true或false
            $mail->addAddress($v);
            $mail->Subject = $subject; //添加该邮件的主题
            $mail->Body = $content; //添加邮件正文 
            $mail->AddAttachment($attachment);
            $state = $mail->send(); //发送命令 返回布尔值 
            $mail->smtpClose();
            $data = [
                'sender_id' => 0,
                'receiver_id' => 0,
                'sender' => $sender,
                'receiver' => $receiver,
                'create_time' => tnow(),
                'department_id' => $this->session->department_id,
                'uid' => $this->session->id,
                'username' => $this->session->username
            ];
            if ($state)
                $data['isok'] = 1;
            $this->log_model->createLog('su_send_record', $data);
        }
        $redata['errno'] = 666;
        $redata['error'] = '邮件发送成功!';
        echo json_encode($redata);
    }

    public function get_task_record() {
        $table = 'su_send_record';
        $where = [
            'department_id' => $this->session->department_id
        ];
        return $this->log_model->getLog($table, $where);
    }

    /*
     * 通过自建服务器发送
     */

    public function masssend_via_mailserver() {
        $redata = $this->httpcode;
        $department_id = $this->session->department_id;
        $uid = $this->session->id;
        $receiver = $this->input->post('receiver');
        $template = $this->input->post('template');
        $subject = $this->input->post('subject');
        $content = $this->input->post('content');
        $where_receive = [
            'department_id' => $department_id,
            'status' => 1,
            'enable' => 1,
            'group_id' => $receiver
        ];

        $this->receiver = $this->address_model->addressInfo('su_receiver', $where_receive);
        $where = [
            'id' => $template
        ];
        $this->subject = $subject;
        $this->content = $content;
        $this->template_content = $this->template_model->getTemplateByid($where);
        $this->request_to_mailserver();
        $redata['errno'] = 666;
        $redata['error'] = '执行任务成功!';
        echo json_encode($redata);
    }

    /*
     * 请求邮件服务器发送邮件
     */

    public function request_to_mailserver() {

        $serverquota = $this->data['webconfig'][2]['value'];
        $mailserver = $this->common_model->getList('su_mailserver', ['department_id' => $this->session->department_id]);
        $attachment = $this->template_content['attachment'];
        $totalreceiver = count($this->receiver); //总的收件人数量
        $leftreceiver = $totalreceiver; //剩余收件人数量

        if (!empty($attachment))
            $attachment = 'http://118.89.233.35:7766/' . $attachment;

        foreach ($mailserver as $rows) {
            $leftquota = $serverquota - $rows['today_usage']; //今日本服务器剩余发送量
            $is_end = 0; //是否结束
            $url = $rows['server_address'];
            $method = 'post';
            $data = [];
            $start = 0; //开始下标
            $end = $leftquota; //结束下标
            //如果本服务器可用
            if ($rows['enable'] == 1 && $is_end == 0) {
                $receiver = array_slice($this->receiver, $start, $end);
                $contentarr = [];
                foreach ($receiver as $k => $v) {
                    $this->template_content['is_messy'] == 1 ? $contentarr[$k] = $this->htmlbefore . add_disturb($this->content) . $this->htmlafter : $contentarr[$k] = $this->htmlbefore . $this->content . $this->htmlafter;
                }
                $start += $leftquota;
                $receiveramount = count($receiver); //收件人数量
                if (count($receiver) == 0) {
                    $is_end == 1;
                }
                $data = [
                    'operatorinfo' => [//操作人信息
                        'department_id' => $this->session->department_id,
                        'uid' => $this->session->id,
                    ],
                    'receiver' => $receiver, //收件人信息
                    'emailinfo' => [//邮件信息
                        'sender' => $this->sendname, //发件人昵称
                        'from' => $rows['server_sender'], //发件邮箱
                        'subject' => $this->subject, //邮件主题
                        'content' => $contentarr, //邮件内容
                        'attachment' => $attachment//附件
                    ]
                ];
                $state = CURLSend($url, $method, $data);
                //创建发送日志
                foreach ($receiver as $vr) {
                    $data = [
                        'sender_id' => $rows['id'],
                        'receiver_id' => $vr['id'],
                        'sender' => $rows['server_sender'],
                        'receiver' => $vr['email'],
                        'create_time' => tnow(),
                        'department_id' => $this->session->department_id,
                        'uid' => $this->session->id,
                        'username' => $this->session->username,
                        'isok' => 1
                    ];

                    $this->log_model->createLog('su_send_record', $data);
                    $where_sender = [
                        'id' => $rows['id']
                    ];
                    $where_receiver = [
                        'id' => $vr['id']
                    ];
                    $senderInfo = $this->address_model->getAddress('su_mailserver', $where_sender);
                    $receiverInfo = $this->address_model->getAddress('su_receiver', $where_receiver);
                    $senderInfo['today_usage'] ++;
                    $senderInfo['total_usage'] ++;
                    $receiverInfo['today_usage'] ++;
                    $receiverInfo['total_usage'] ++;
                    $data_sender = [
                        'today_usage' => $senderInfo['today_usage'],
                        'total_usage' => $senderInfo['total_usage']
                    ];
                    if ($senderInfo['today_usage'] >= $this->data['webconfig'][2]['value'])
                        $data_sender['enable'] = 0;
                    $data_receiver = [
                        'today_usage' => $receiverInfo['today_usage'],
                        'total_usage' => $receiverInfo['total_usage']
                    ];
                    if ($receiverInfo['today_usage'] >= $this->data['webconfig'][1]['value'])
                        $data_receiver['enable'] = 0;
                    $this->address_model->updateAddress('su_mailserver', $where_sender, $data_sender);
                    $this->address_model->updateAddress('su_receiver', $where_receiver, $data_receiver);
                }
            }
        }
    }

    /*
     * 通过自建服务器发送
     */

    public function send_via_mailserver() {
        $redata = $this->httpcode;
        $department_id = $this->session->department_id;
        $uid = $this->session->id;
        $where_receive = [
            'department_id' => $department_id,
            'status' => 1
        ];
        $receiver = $this->input->post('receiver');
        $subject = $this->input->post('subject');
        $content = $this->input->post('content');
        $attachment = $this->input->post('attachment');

        $this->receiver = explode(';', $receiver);
        foreach ($this->receiver as $k => $rows) {
            $this->receiver[$k] = ['email' => $rows];
        }
        $this->subject = $subject;
        $this->content = $content;
        $this->attachment = $attachment;
        $this->normalrequest_to_mailserver();
        $redata['errno'] = 666;
        $redata['error'] = '邮件发送成功!';
        echo json_encode($redata);
    }

    public function normalrequest_to_mailserver() {
        $serverquota = $this->data['webconfig'][2]['value'];
        $mailserver = $this->common_model->getList('su_mailserver', ['department_id' => $this->session->department_id]);
        $totalreceiver = count($this->receiver); //总的收件人数量
        $leftreceiver = $totalreceiver; //剩余收件人数量
        if (!empty($this->attachment))
            $this->attachment = base_url() . $this->attachment;
        foreach ($mailserver as $rows) {
            $leftquota = $serverquota - $rows['today_usage']; //今日本服务器剩余发送量
            $is_end = 0; //是否结束
            $url = $rows['server_address'];
            $method = 'post';
            $data = [];
            $start = 0; //开始下标
            $end = $leftquota; //结束下标
            //如果本服务器可用
            if ($rows['enable'] == 1 && $is_end == 0) {
                $receiver = array_slice($this->receiver, $start, $end);
                $contentarr = [];
                foreach ($receiver as $k => $v) {
                    $contentarr[$k] = $this->content;
                }
                $start += $leftquota;
                $receiveramount = count($receiver); //收件人数量
                if (count($receiver) == 0) {
                    $is_end == 1;
                }
                $data = [
                    'operatorinfo' => [//操作人信息
                        'department_id' => $this->session->department_id,
                        'uid' => $this->session->id,
                    ],
                    'receiver' => $receiver, //收件人信息
                    'emailinfo' => [//邮件信息
                        'sender' => $this->sendname, //发件人昵称
                        'from' => $rows['server_sender'], //发件邮箱
                        'subject' => $this->subject, //邮件主题
                        'content' => $contentarr, //邮件内容
                        'attachment' => $this->attachment//附件
                    ]
                ];
                $state = CURLSend($url, $method, $data);
                //创建发送日志
                foreach ($receiver as $k => $vr) {
                    $data = [
                        'sender_id' => $rows['id'],
                        'receiver_id' => 0,
                        'sender' => $rows['server_sender'],
                        'receiver' => $vr['email'],
                        'create_time' => tnow(),
                        'department_id' => $this->session->department_id,
                        'uid' => $this->session->id,
                        'username' => $this->session->username,
                        'isok' => 1
                    ];

                    $this->log_model->createLog('su_send_record', $data);
                    $where_sender = [
                        'id' => $rows['id']
                    ];
                    $senderInfo = $this->address_model->getAddress('su_mailserver', $where_sender);
                    $senderInfo['today_usage'] ++;
                    $senderInfo['total_usage'] ++;
                    $data_sender = [
                        'today_usage' => $senderInfo['today_usage'],
                        'total_usage' => $senderInfo['total_usage']
                    ];
                    if ($senderInfo['today_usage'] >= $this->data['webconfig'][2]['value'])
                        $data_sender['enable'] = 0;
                    $this->address_model->updateAddress('su_mailserver', $where_sender, $data_sender);
                }
            }
        }
    }

    public function cleanlog() {
        $redata = $this->httpcode;
        $cleantype = $this->input->post('cleantype');
        $department_id = $this->session->department_id;
        $stime = date('Y-m-d') . ' 00:00:00';
        $etime = date('Y-m-d') . ' 23:59:00';
        if ($cleantype == 1) {

            $where = "department_id=$department_id AND create_time>'$stime' AND create_time<'$etime'";
        } else {
            $where = "department_id=$department_id AND create_time<'$stime'";
        }
        $this->db->where($where)->delete('su_send_record');
        if ($this->db->affected_rows()) {
            $redata['errno'] = '666';
            $redata['error'] = '操作成功';
        } else {
            $redata['errno'] = '666';
            $redata['error'] = '没有数据需要清除';
        }
        echo json_encode($redata);
    }

}
